package com.jzg.jcptadmin.ui;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.jzg.jcptadmin.R;
import com.jzg.jcptadmin.Utils.MD5Utils;
import com.jzg.jcptadmin.Utils.MyToast;
import com.jzg.jcptadmin.app.ActivityHelp;
import com.jzg.jcptadmin.base.BaseActivity;
import com.jzg.jcptadmin.data.DataManager;
import com.jzg.jcptadmin.data.local.ACache;
import com.jzg.jcptadmin.data.vo.User;
import com.jzg.jcptadmin.presenter.MainPresenter;
import com.jzg.jcptadmin.presenter.StatusPresenter;
import com.jzg.jcptadmin.viewinterface.MainActivityInterface;
import com.jzg.jcptadmin.viewinterface.StatusInterface;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * 登陆
 * MainActivity
 *
 * @author sunbl
 *         created at 2016/1/21 16:10
 */
public class MainActivity extends BaseActivity implements MainActivityInterface, View.OnClickListener, StatusInterface {

    @Bind(R.id.username)
    EditText mUserName;
    @Bind(R.id.password)
    EditText mPassword;
    @Bind(R.id.login_btn)
    Button mLoginBtn;

    protected SharedPreferences userInfo;
    @Bind(R.id.username_label)
    ImageView usernameLabel;
    @Bind(R.id.un_clear)
    ImageView unClear;
    @Bind(R.id.pwd_label)
    ImageView pwdLabel;
    @Bind(R.id.pwd_clear)
    ImageView pwdClear;
    @Bind(R.id.show_pwd)
    ImageView showPwd;
    private String name = "";
    private String pass;
    private String requestUsername = "";
    private String requestPass = "";
    private MainPresenter mMainPresenter;
    public boolean isLogout = true;  //退出登录标记 true登陆 退出false
    private StatusPresenter statusPresenter;
    private String JpushId;
    private boolean isShowPwd = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        //保存状态的P层
        statusPresenter = new StatusPresenter(DataManager.getInstance(), appContext);
        statusPresenter.attachView(this);
//        if(AppContext.httpService==null){
//            appContext.initHttp();
//        }
        statusPresenter.LoadStatusData();
        JpushId = JPushInterface.getRegistrationID(appContext);
        mMainPresenter = new MainPresenter(DataManager.getInstance());
        mMainPresenter.attachView(this);
        isLogout = getIntent().getBooleanExtra("edit", true);
        userInfo = getSharedPreferences("user_info", 0);
        name = userInfo.getString("name", "");
        pass = userInfo.getString("password", "");
        mMainPresenter.isLogout(isLogout);
        initListener();
    }

    private void initListener() {

        mUserName.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus){
                    unClear.setVisibility(View.VISIBLE);
                    mUserName.setSelection(mUserName.getText().toString().length());//将光标移至文字末尾
                }else{
                    unClear.setVisibility(View.INVISIBLE);
                }
            }
        });

        mUserName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(s.toString())){
                    unClear.setVisibility(View.INVISIBLE);
                }else{
                    unClear.setVisibility(View.VISIBLE);
                }
            }
        });

        mPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(s.toString())){
                    pwdClear.setVisibility(View.INVISIBLE);
                }else{
                    pwdClear.setVisibility(View.VISIBLE);
                }
            }
        });

        mPassword.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus){
                    pwdClear.setVisibility(View.VISIBLE);
                }else{
                    pwdClear.setVisibility(View.INVISIBLE);
                }
            }
        });
    }

    private void initView() {
        mUserName.setText(name);
        if (isLogout) {
            mPassword.setText(pass);
        } else {
            mPassword.setText("");
        }
    }

    /**
     * 登陆
     */
    private void clickLoginBtn() {
        requestUsername = mUserName.getText().toString();
        requestPass = mPassword.getText().toString();
        if (!checkForForm()) {
            saveUsername(requestUsername, requestPass);
            showDialog();
            mMainPresenter.login();
        }
    }

    /**
     * 校验用户名密码是否为空
     */
    private boolean checkForForm() {
        String username = mUserName.getText().toString().trim();
        String password = mPassword.getText().toString().trim();
        if (TextUtils.isEmpty(username)) {

            MyToast.showShort("请输入用户名");
            return true;
        }
        if (TextUtils.isEmpty(password)) {

            MyToast.showShort("请输入密码");
            return true;
        }
        return false;
    }

    /**
     * 保存用户名、密码信息
     */
    private void saveUsername(String user, String pass) {
        userInfo.edit().putString("name", user).putString("password", pass)
                .commit();
    }

    @Override
    public void success(User user) {
        //跳转到首页
        ActivityHelp.startActivity(this, HomeActivity.class);
      /*  if (user.getIsDL().equals("1")) {
            ActivityHelp.startActivity(this, YiXinHomeActivity.class);
            overridePendingTransition(android.R.anim.fade_in,android.R.anim.fade_out);
        } else {
            ActivityHelp.startActivity(this, HomeActivity.class);
        }*/
        //保存userId
        mMainPresenter.savaUser(appContext, user);
        JPushInterface.resumePush(getApplicationContext());
        if ("0".equals(user.getJpushRegister())) {
            setJPushTag(user);
        } else {
            finish();
        }


//        wyd 修改MainActivity leaked64mb问题
//        finish();
    }

    /**
     * 设置激光推送别名
     *
     * @param user
     */
    private void setJPushTag(final User user) {
        Set<String> tagSet = new HashSet<String>();
//        tagSet.add("test" + String.valueOf(user.getUserId()));//测试环境
        tagSet.add(String.valueOf(user.getUserId()));//正式环境
        JPushInterface.setTags(getApplicationContext(), tagSet, new TagAliasCallback() {
            @Override
            public void gotResult(int i, String s, Set<String> set) {
                if (i == 0) {  //成功
                    finish();
                } else if (i == 6002) {
                    Observable.timer(10, TimeUnit.SECONDS, AndroidSchedulers.mainThread())
                            //observeOn(): 指定 Subscriber 所运行在的线程。或者叫做事件消费的线程。下面的call方法会在io线程中执行
                            .observeOn(Schedulers.io())
                            //subscribeOn(): 指定 subscribe() 所发生的线程，即 Observable.OnSubscribe 被激活时所处的线程。或者叫做事件产生的线程。
                            .subscribeOn(Schedulers.io())
                            .subscribe(new Action1<Long>() {
                                @Override
                                public void call(Long s) {
                                    Set<String> tagSet = new HashSet<String>();
//                                    tagSet.add("test" + String.valueOf(user.getUserId()));//测试环境
                                    tagSet.add(String.valueOf(user.getUserId()));//正式环境
                                    JPushInterface.setTags(getApplicationContext(), tagSet, null);
                                }
                            });
                } else {
                    MyToast.showShort("设置推送失败");
                    finish();
                }

            }
        });
        JPushInterface.resumePush(getApplicationContext());
    }


    @Override
    public void failed(String error) {
        dismissDialog();
        ACache.get(this).remove("User");
        MyToast.showShort(error);
    }

    /**
     * 自动登陆
     */
    @Override
    public void autoLogin() {
        initView();
        if (!TextUtils.isEmpty(name)) {
//            clickLoginBtn();
        }
    }

    /**
     * 退出登陆
     */
    @Override
    public void exitLogin() {
        initView();
        userInfo.edit().putString("password", "").commit();
    }

    /**
     * 获取登陆参数
     *
     * @return
     */
    @Override
    public Map<String, String> getLoginParams() {
        Map<String, String> params = new HashMap<String, String>();
        params.put("lgcode", requestUsername);
        params.put("pwd", requestPass);
        params.put("op", "login");
        params.put("tokenid", "6");
        if (!TextUtils.isEmpty(JpushId)) {
            params.put("registrationId", JpushId);
        }
        Map<String, Object> signMap = new HashMap<>();
        signMap.putAll(params);
        params.put("sign", MD5Utils.getMD5Sign(signMap));
        return params;
    }

//    private void regestJiguang() {
//        Observable.timer(10, TimeUnit.SECONDS, AndroidSchedulers.mainThread())
//                //observeOn(): 指定 Subscriber 所运行在的线程。或者叫做事件消费的线程。下面的call方法会在io线程中执行
//                .observeOn(Schedulers.io())
//                //subscribeOn(): 指定 subscribe() 所发生的线程，即 Observable.OnSubscribe 被激活时所处的线程。或者叫做事件产生的线程。
//                .subscribeOn(Schedulers.io())
//                .subscribe(new Action1<Long>() {
//                    @Override
//                    public void call(Long s) {
//                        Set<String> tagSet = new HashSet<String>();
////                                    tagSet.add("test" + String.valueOf(user.getUserId()));//测试环境
//                        tagSet.add(String.valueOf(user.getUserId()));//正式环境
//                        JPushInterface.setTags(getApplicationContext(), tagSet, null);
//                    }
//                });
//    }


    @Override
    @OnClick({R.id.login_btn,R.id.show_pwd,R.id.pwd_clear,R.id.un_clear})
    public void onClick(View v) {

        switch (v.getId()){
            case R.id.login_btn:
                //第一次登录流程
//        mPassword.setText("jcpt@wsx#");//TODO pk clear when wrapper
                clickLoginBtn();
                break;

            case R.id.show_pwd:
          hanlePwdVisiable();
                break;
            case R.id.pwd_clear:

                if (!TextUtils.isEmpty(mPassword.getText().toString())){
                    mPassword.setText("");
                }
                break;
            case R.id.un_clear:
                if (!TextUtils.isEmpty(mUserName.getText().toString())){
                    mUserName.setText("");
                }
                break;
            default:

                break;
        }
    }


    private void hanlePwdVisiable() {
        if (isShowPwd) {
            // hide password, display "."
            mPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
//            mPassword.setSelection(mPassword.getText().toString().length());//将光标移至文字末尾
            showPwd.setImageResource(R.drawable.pwd_tip_normal);

        } else {
            // display password text, for example "123456"
            mPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
//            mPassword.setSelection(mPassword.getText().toString().length());//将光标移至文字末尾
            showPwd.setImageResource(R.drawable.pwd_tip_press);
        }
        mPassword.setSelection(mPassword.getText().toString().length());//将光标移至文字末尾
        isShowPwd = !isShowPwd;
        mPassword.postInvalidate();
    }
   /* //加载状态的回调
    @Override
    public void ShowData(StatusData statusData) {
        if (statusData.getStatus() == Constant.SUCCESS) {
            statusPresenter.savaStatus(appContext, statusData);

        }
    }*/

    /**
     * 获取加载状态参数
     */
    @Override
    public Map<String, String> getLoadStatusParams() {
        Map<String, String> params = new HashMap<String, String>();
        params.put("tokenid", "6");
        Map<String, Object> signMap = new HashMap<>();
        signMap.putAll(params);
        params.put("sign", MD5Utils.getMD5Sign(signMap));
        return params;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
        if (mMainPresenter != null)
            mMainPresenter.detachView();
        if (statusPresenter != null)
            statusPresenter.detachView();
    }
}
